﻿using Bilibili.WebClient;
using LibVLCSharp.Shared;
using System;
using System.Diagnostics;

namespace Avalonia.BiliBili.Libs.Medias
{
    public sealed class AudioPlayer
    {
        private static AudioPlayer instance;
        public static AudioPlayer Instance => instance ??= new AudioPlayer();
        private LibVLC LibVlc { get; }
        private MediaPlayer MediaPlayer { get; }
        private AudioPlayer()
        {
            LibVlc = new LibVLC();
            LibVlc.SetUserAgent("bilibili", Current.PLAY_USER_AGENT);
            if (Debugger.IsAttached)
                LibVlc.Log += LibVlc_Log;
            MediaPlayer = new MediaPlayer(LibVlc) { EnableHardwareDecoding = true };
        }
        private void LibVlc_Log(object sender, LogEventArgs e)
        {
            Debug.WriteLine(e.Message);
        }
        public bool Play(string audioUrl, out string message)
        {
            try
            {
                var mediaItem = new MediaItem(LibVlc, new Uri(audioUrl));
                MediaPlayer.Play(mediaItem);
                message = string.Empty;
                return true;
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return false;
            }
        }
        public void Pause()
        {
            try
            {
                MediaPlayer.Pause();
            }
            catch { }
        }
        public void Stop()
        {
            try
            {
                MediaPlayer.Stop();
            }
            catch { }
        }
        public void Dispose()
        {
            try
            {
                MediaPlayer?.Dispose();
                LibVlc?.Dispose();
            }
            catch { }
        }
    }
}